import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}, // 为了后续放个人信息
  routes: constantRoutes
}

const mutations = {
  setToken(state, token) {
    // 设置到vuex中
    state.token = token
    // 设置到本地存储cookie中
    setToken(token)
  },
  // 删除vuex及本地token
  removeToken(state, token) {
    state.token = null
    removeToken()
  },
  // 设置userInfo的mutation
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  // 登录
  async login(context, data) {
    // todo 调接口 (模拟一下,接口还没准备好)
    console.log(data)
    // const {token} = await login(data)
    const token = await login(data)
    context.commit('setToken', token)
  },
  // 获取个人信息
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result
  },
  // 退出登录
  logout(context) {
    // 清空token  清空userInfo
    context.commit('removeToken')
    context.commit('setUserInfo', {})
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
